package com.zsh.webfluxdemo1.handler;

import com.zsh.webfluxdemo1.entity.User;
import com.zsh.webfluxdemo1.service.UserService;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.function.server.ServerResponseExtensionsKt;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.BodyInserters.fromObject;

/**
 * @author zsh
 * @Description
 * @create 2022-03-07 19:55
 */
public class UserHandler {

    private final UserService userService;

    public UserHandler(UserService userService){
        this.userService = userService;
    }

    //根据id查询
    public Mono<ServerResponse> getUserById(ServerRequest request) {
        //获取id
        int userId = Integer.parseInt(request.pathVariable("id"));

        //空值处理
        Mono<ServerResponse> notFound = ServerResponse.notFound().build();

        //调用service
        Mono<User> userMono = this.userService.getUserById(userId);

        //把userMono转为ServerResponse
        //使用Reactor 操作符flatmap

        return
                userMono.flatMap(person -> ServerResponse.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(fromObject(person)))
                        .switchIfEmpty(notFound);
    }

    //查询所有
    public Mono<ServerResponse> getAllUsers(ServerRequest request){
        Flux<User> users = this.userService.getAllUser();
        return
                ServerResponse.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(users,User.class);
    }

    //添加
    public Mono<ServerResponse> saveUser(ServerRequest request){
        //得到user对象
        Mono<User> userMono = request.bodyToMono(User.class);

        return ServerResponse.ok().build(this.userService.saveUserInfo(userMono)); //build 表示进行订阅
    }
}
